package com.xzh.job;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xzh.constant.RedisConstants;
import com.xzh.util.AliOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;

//SpringTask
@Configuration
public class DeleteImageJob {
    private RedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Scheduled(cron = "0 */5 * * * *")
    public void deleteImage() {
        System.out.println("DeleteImageJob.deleteImage");
        Set<String> dbSet = redisTemplate.opsForSet().members(RedisConstants.UPLOAD_IMAGE_TO_DB);
        Set<String> set = redisTemplate.opsForSet().difference(RedisConstants.UPLOAD_IMAGE, RedisConstants.UPLOAD_IMAGE_TO_DB);
        if (!CollectionUtils.isEmpty(dbSet) && !CollectionUtils.isEmpty(set)) {
            for (String url : set) {
                AliOSSUtil.deleteFile(url);
                System.out.println("删除图片：" + url);
            }
            //删除redis中图片
            redisTemplate.delete(RedisConstants.UPLOAD_IMAGE);
            redisTemplate.delete(RedisConstants.UPLOAD_IMAGE_TO_DB);
        }
    }
}
